<template>
  <rk-top-bottom-container :isFooter="false"
    :isAside="false">
    <template #header_left>
    </template>
    <template #header_right>
      <el-button type="primary"
        @click="handleOperation('add')">录入
      </el-button>
      <el-button @click="handleOperation('edit','修改')">修改
      </el-button>
      <el-button @click="handleOperation('setting','评分配置')">评分配置
      </el-button>
      <el-button type="danger"
        @click="handleOperation('delete', '删除')">删除
      </el-button>
    </template>
    <template #main_top>
      <rk-center>
        <template #content>
          <rk-grid ref="expertManageRef"
            title="专家信息维护"
            dataUrl="/expert/page"
            boxConfig
            :params="queryParams"
            :columns="expertColumns"
            :row-config="{isCurrent: true, isHover: true}"
            @current-change="onCurrentChange">
            <template #toolbar_title_buttons>
              <el-input v-model="queryParams.mhcx"
                placeholder="请输入专家名称"
                class="w-200px"
                clearable
                @input="handleSearch" />
            </template>
            <template #status="{ row }">
              <el-tag :type="COMMON_STOP_OPEN_ENUMS.options[row.status].tagType"
                class="mx-1"
                effect="plain">
                {{ COMMON_STOP_OPEN_ENUMS.options[row.status].echo }}
              </el-tag>
            </template>
          </rk-grid>
        </template>
      </rk-center>
    </template>
    <template #main_bottom>
      <rk-center>
        <template #content>
          <rk-grid ref="expertRuleManageRef"
            title="专家规则维护"
            :data="currentExpertRuleData"
            :seq-config="false"
            :loading="ruleLoading"
            :pager-config="false"
            height="auto"
            :auto-resize="true"
            :columns="ruleColumns">
          </rk-grid>
        </template>
      </rk-center>
    </template>
    <OperationLog ref="OperationLogRef" />
  <ExpertManageDialog ref="expertManageDialogRef"
    :ok="okDialog" />
  <ExpertRuleManageDialog ref="expertRuleManageDialogRef"
    :ok="saveRuleCallback" />
  </rk-top-bottom-container>
</template>
<script setup>
import { ElMessage } from "element-plus";
import { useRoute } from 'vue-router'
import { COMMON_STOP_OPEN_ENUMS } from '@/enums/enums-common.js'
import { RkConfirmBox } from '@/components/message-box'
import { useUserStore } from '@/stores/modules';
import ExpertManageDialog from "./dialog/ExpertManageDialog.vue";
import ExpertRuleManageDialog from "./dialog/ExpertRuleManageDialog.vue";

import { useExpertsApi } from '@/api/index'
const  {
  expertManageAssignRuleList,
  expertManageDelete,
  expertManageDetailInfo,
  expertManageSave
} = useExpertsApi();

const OperationLogRef = ref(null)
const { appContext } = getCurrentInstance();
const globalProxy = appContext.config.globalProperties;
const expertManageRef = ref(null)
const ruleLoading = ref(false)

const userStore = useUserStore();
const userInfo = userStore.userInfo
const route = useRoute()
const formCode = route.query.formCode
const currentExpertRuleData = ref([])
const queryParams = reactive({
  mhcx: ''
})
const expertManageDialogRef = ref()
const expertRuleManageDialogRef = ref()

const processKey = ref(null)
processKey.value = queryParams.processKey
const expertColumns = ref([
  { field: 'adName', title: '区划', width: 180, align: 'left', },
  {
    field: 'name',
    title: '专家名称',
    width: 250,
    align: 'left',
  },
  // {field: 'code', title: '登录账号', width: 200, align: 'left',},
  { field: 'phone', title: '联系电话', width: 150, align: 'left', },
  { field: 'idCard', title: '身份证号码', width: 220, align: 'left', },
  {
    field: 'email',
    title: '邮箱',
    width: 150,
    align: 'left'
  },
  {
    field: 'sex', title: '性别', width: 100, align: 'center',
    formatter: ({ cellValue }) => {
      let sex = cellValue
      if (sex) {
        sex = cellValue == 1 ? '男' : '女'
      } else {
        sex = ''
      }
      return sex
    }
  },
  {
    field: 'age', title: '年龄', width: 100, align: 'center'
  },
  {
    field: 'education',
    title: '学历',
    width: 150,
    align: 'center',
    formatter: ({ cellValue }) => {
      if (cellValue == 1) {
        return "专科"
      } else if (cellValue == 2) {
        return "本科"
      } else if (cellValue == 3) {
        return '硕士'
      } else if (cellValue == 4) {
        return "博士"
      }
      return cellValue
    }

  },
  {
    field: 'unit', title: '工作单位', width: 150, align: 'center'
  },
  { field: 'title', title: '职称', width: 100, align: 'center' },
  { field: 'introduction', title: '简介', width: 150, align: 'left' },
  {
    field: 'status', title: '状态', width: 200, align: 'center', formatter: ({ cellValue }) => {
      return cellValue == 1 ? '启用' : '停用'
    }
  }]
)


const ruleColumns = ref([
  {
    field: 'entryLev1',
    title: '一级条目',
    width: 250,
    align: 'left',
  },
  { field: 'entryLev2', title: '二级条目', width: 200, align: 'left', },
  { field: 'reviewDesc', title: '评审内容', width: 550, align: 'left', },
  { field: 'reviewStandard', title: '评审标准', width: 220, align: 'center', },
  {
    field: 'scoreType',
    title: '评分选项',
    width: 120,
    align: 'center',
    formatter: ({ cellValue }) => {
      return cellValue == 1 ? '分数' : '是/否'
    }
  },
  {
    field: 'scoreRange', title: '分值', width: 200, align: 'center',
    formatter: ({ cellValue, row }) => {
      return row.scoreType == 1 ? cellValue : '--'
    }
  },
  {
    field: 'remark', title: '备注', width: 100, align: 'left'
  },
])
/**查询 */
const handleSearch = () => {
  expertManageRef.value.searchEvent()
  //清空规则列表
  currentExpertRuleData.value = []

}

const handleOperation = async (buttonType, textName) => {
  if (buttonType === 'edit' || buttonType === 'add' || buttonType === 'setting') { //修改
    if (buttonType === 'add') {
      let data = { adName: userInfo.adName, AD_CODE: userInfo.adCode }
      expertManageDialogRef.value.handleOpen(buttonType, data)
    } else if (buttonType === 'edit') {
      const seleRows = expertManageRef.value.getCheckboxRecords()
      if (!seleRows || seleRows.length !== 1) {
        ElMessage.warning({ message: `请选择一条数据进行${textName}！` })
        return
      }
      let expertId = seleRows[0].expertId
      let params = { formCode, expertId }
      expertManageDetailInfo(params).then((resp) => {
        if (resp.code === 200) {
          expertManageDialogRef.value.handleOpen(buttonType, resp.data)
        } else {
          ElMessage.error({ message: "获取专家详细信息错误" })
        }
      })
    } else if (buttonType === 'setting') {
      const seleRows = expertManageRef.value.getCheckboxRecords()
      if (!seleRows || seleRows.length !== 1) {
        ElMessage.warning({ message: `请选择一条数据进行${textName}！` })
        return
      }
      expertRuleManageDialogRef.value.handleOpen(seleRows[0])
    }
    return
  } else {
    const seleRows = expertManageRef.value.getCheckboxRecords()
    if (!seleRows || seleRows.length === 0) {
      ElMessage.warning({ message: `请至少选择一条数据进行${textName}！` })
      return
    }
    RkConfirmBox({
      title: '提示',
      content: `您确定要${textName}吗？`,
      onSubmit: async function () {
        if (buttonType == 'delete') {//删除
          let expertIds = seleRows.map(item => {
            return item.expertId
          })
          expertManageDelete({ expertIds: expertIds.join(",") }).then(resp => {
            if (resp.code === 200) {
              ElMessage.success("删除成功")
              handleSearch()
              return
            }
            ElMessage.success("删除失败")
          })
        }
      },
      onCancel: function () {

      }
    })
  }
}
//修改/添加保存
const okDialog = (formType, data) => {
  return new Promise((resolve, reject) => {
    data.field
    expertManageSave({ data }).then((resp) => {
      if (resp.code === 200) {
        ElMessage.success({ message: '保存成功' })
        resolve()
        handleSearch()
        return
      } else {
        ElMessage.error({ message: resp.msg || '保存失败' })
      }

    })

  })
}
//操作记录
const handleOpenRecord = () => {
  const seleRows = expertManageRef.value.getCheckboxRecords()
  if (seleRows.length == 0 || !seleRows || seleRows.length > 1) {
    globalProxy.$message({ message: "请选择一条数据！", type: "warning" });
    return;
  }
  let applyId = ''
  seleRows.forEach(element => {
    applyId = element.applyId
  });
  OperationLogRef.value.handleOpen(applyId)
}
const onCurrentChange = ({ row }) => {
  ruleLoading.value = true
  expertManageAssignRuleList(row.expertId).then(resp => {
    if (resp.code === 200) {
      if (resp.data) {
        currentExpertRuleData.value = resp.data
        ruleLoading.value = false
        return
      }
    }
    currentExpertRuleData.value = []
    ruleLoading.value = false
  })
}
const saveRuleCallback = () => {
  handleSearch()
}
const handleRefresh = () => {
  handleSearch()
}

</script>

<style lang="scss" scoped>
.w-200px {
  width: 200px;
}
</style>
